package com.yanqu.road.dao.impl.union.cross;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.UnionConstruct;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossUnionMemberDaoImpl extends TempDataObjectDao<CrossUnionMember> {

	public Map<Long, CrossUnionMember> getUnionMemberMap(Map<String, Map<Long, CrossUnionMember>> unionMemberMap, Map<Long, CrossUnionMember> deleteMemberMap) {
		ResultSet rs = null;
		CallableStatement call = null;
		String sql = "SELECT * FROM t_c_union_member";
		Map<Long, CrossUnionMember> dataMap = new ConcurrentHashMap<>();
		try {
			getDb().setConnName(DbNameStrategy.getCross2Db());
			call = getDb().getConnection().prepareCall(sql);
			rs = call.executeQuery();
			while (rs.next()) {
				CrossUnionMember data = parse(rs);
				dataMap.put(data.getUserId(), data);
				if(!StringUtils.isNullOrEmpty(data.getUnionUid())){
					if(!unionMemberMap.containsKey(data.getUnionUid())){
						unionMemberMap.put(data.getUnionUid(), new ConcurrentHashMap<>());
					}
					if(!unionMemberMap.get(data.getUnionUid()).containsKey(data.getUserId())) {
						unionMemberMap.get(data.getUnionUid()).put(data.getUserId(), data);
					}
				}else {
					if(!deleteMemberMap.containsKey(data.getUserId())) {
						deleteMemberMap.put(data.getUserId(), data);
					}
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			getDb().closeConnection(call, rs);
		}
		return dataMap;
	}

	@Override
	protected boolean addData(CrossUnionMember data) {
		PreparedStatement call = null;
		String sql = "INSERT INTO t_c_union_member(unionUid,userId,position,userBaseInfo,modifyTime,contribution,totalContribution,"
				+ "donateTimes,quitTime,kickTime,joinTime,dayKickNum,unionConstructData,constructRewardIndexList,todayContribution,chamberPatronsId,serverId,dayCoolingOffNotice,historyMaxAbility,monthAbilityRank,abilityRankGrade) VALUES "
				+ "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		try {
			getDb().setConnName(DbNameStrategy.getCross2Db());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, data.getUnionUid());
			call.setLong(i++, data.getUserId());
			call.setInt(i++, data.getPosition());
			call.setString(i++, data.getUserBaseInfoJsonStr());
			call.setLong(i++, data.getModifyTime());
			call.setLong(i++, data.getContribution());
			call.setLong(i++, data.getTotalContribution());
			call.setInt(i++, data.getDonateTimes());
			call.setLong(i++, data.getQuitTime());
			call.setLong(i++, data.getKickTime());
			call.setLong(i++, data.getJoinTime());
			call.setInt(i++, data.getDayKickNum());
			call.setString(i++, data.getUnionConstructMapJson());
			call.setString(i++, data.getConstructRewardIndexListString());
			call.setInt(i++, data.getTodayContribution());
			call.setInt(i++, data.getChamberPatronsId());
			call.setLong(i++, data.getServerId());
			call.setBoolean(i++, data.getDayCoolingOffNotice());
			call.setString(i++, data.getHistoryMaxAbility().toString());
			call.setInt(i++, data.getMonthAbilityRank());
			call.setInt(i++, data.getAbilityRankGrade());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected boolean updateData(CrossUnionMember data) {
		PreparedStatement call = null;
		String sql = "UPDATE t_c_union_member SET unionUid=?,position=?,userBaseInfo=?,modifyTime=?,contribution=?,"
				+ "totalContribution=?,donateTimes=?,quitTime=?,kickTime=?,joinTime=?,dayKickNum=?,unionConstructData=?,constructRewardIndexList=?,todayContribution=?,"
				+ "chamberPatronsId=?,serverId=?,dayCoolingOffNotice=?,historyMaxAbility=?,monthAbilityRank=?,abilityRankGrade=? WHERE userId=?";
		try {
			getDb().setConnName(DbNameStrategy.getCross2Db());
			call = getDb().getConnection().prepareStatement(sql);
			int i = 1;
			call.setString(i++, data.getUnionUid());
			call.setInt(i++, data.getPosition());
			call.setString(i++, data.getUserBaseInfoJsonStr());
			call.setLong(i++, data.getModifyTime());
			call.setLong(i++, data.getContribution());
			call.setLong(i++, data.getTotalContribution());
			call.setInt(i++, data.getDonateTimes());
			call.setLong(i++, data.getQuitTime());
			call.setLong(i++, data.getKickTime());
			call.setLong(i++, data.getJoinTime());
			call.setInt(i++, data.getDayKickNum());
			call.setString(i++, data.getUnionConstructMapJson());
			call.setString(i++, data.getConstructRewardIndexListString());
			call.setInt(i++, data.getTodayContribution());
			call.setInt(i++, data.getChamberPatronsId());
			call.setLong(i++, data.getServerId());
			call.setBoolean(i++, data.getDayCoolingOffNotice());
			call.setString(i++, data.getHistoryMaxAbility().toString());
			call.setInt(i++, data.getMonthAbilityRank());
			call.setInt(i++, data.getAbilityRankGrade());

			call.setLong(i++, data.getUserId());
			return call.executeUpdate() > 0;
		} catch (Exception e) {
			logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
		} finally {
			getDb().closeConnection(call, null);
		}
		return false;
	}

	@Override
	protected CrossUnionMember parseData(ResultSet rs) throws SQLException {
		CrossUnionMember data = new CrossUnionMember();
		data.setUnionUid(rs.getString("unionUid"));
		data.setUserId(rs.getLong("userId"));
		data.setPosition(rs.getInt("position"));
		String baseUserInfoStr = rs.getString("userBaseInfo");
		if(null == baseUserInfoStr){
			baseUserInfoStr = "";
		}
		UserBaseInfo userBaseInfo = JSON.parseObject(baseUserInfoStr, new TypeReference<UserBaseInfo>() {});
		if(null != userBaseInfo) {
			data.setUserBaseInfo(userBaseInfo);
		}
		data.setModifyTime(rs.getLong("modifyTime"));
		data.setContribution(rs.getLong("contribution"));
		data.setTotalContribution(rs.getLong("totalContribution"));
		data.setDonateTimes(rs.getInt("donateTimes"));
		data.setQuitTime(rs.getLong("quitTime"));
		data.setKickTime(rs.getLong("kickTime"));
		data.setJoinTime(rs.getLong("joinTime"));
		data.setDayKickNum(rs.getInt("dayKickNum"));
		data.setTodayContribution(rs.getInt("todayContribution"));
		data.setChamberPatronsId(rs.getInt("chamberPatronsId"));
		data.setConstructRewardIndexList(StringUtils.stringToIntegerList(rs.getString("constructRewardIndexList"), ","));
		String unionConstructData = rs.getString("unionConstructData");
		Map<Integer, UnionConstruct> unionConstructMap = new ConcurrentHashMap<>();
		if(!StringUtils.isNullOrEmpty(unionConstructData)){
			unionConstructMap = JSON.parseObject(unionConstructData, new TypeReference<Map<Integer, UnionConstruct>>() {});
		}
		data.setUnionConstructMap(unionConstructMap);
		data.setServerId(rs.getLong("serverId"));
		data.setDayCoolingOffNotice(rs.getBoolean("dayCoolingOffNotice"));
		String ability = rs.getString("historyMaxAbility");
		if(!StringUtils.isNullOrEmpty(ability)) {
			data.setHistoryMaxAbility(new BigInteger(ability));
		}
		data.setMonthAbilityRank(rs.getInt("monthAbilityRank"));
		data.setAbilityRankGrade(rs.getInt("abilityRankGrade"));
		return data;
	}
}
